package org.example.steamshop.controller;


import org.example.steamshop.form.LoginForm;
import org.example.steamshop.model.User;
import org.example.steamshop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public String registerForm() {
        return "register";
    }

    @PostMapping("/register")
    public String registerSubmit(@ModelAttribute LoginForm form) {
        User user = new User();
        user.setUsername(form.getUsername());
        user.setEmail(form.getEmail());
        user.setPassword(form.getPassword());

        // 检查用户名、邮箱是否已存在
        if (userService.existsByUsername(user.getUsername()) || userService.existsByEmail(user.getEmail())) {
            return "redirect:/register?error";
        }

        userService.registerUser(user);
        return "redirect:/login";
    }

    @GetMapping("/login")
    public String loginForm() {
        return "login";
    }

    @PostMapping("/login")
    public String loginSubmit(@RequestParam String username,
                              @RequestParam String password,
                              HttpSession session) {
        User user = userService.findByUsername(username);
        if (user != null && password.equals(user.getPassword())) {
            session.setAttribute("userId", user.getId());
            session.setAttribute("username", user.getUsername());
            session.setAttribute("userRole", user.getRole()); // 存储用户角色到session

            // 根据角色决定跳转页面
            if (User.Role.ADMIN.equals(user.getRole())) {
                return "redirect:/admin/games"; // 管理员页面
            } else {
                return "redirect:/games"; // 普通用户页面
            }
        }
        return "redirect:/login?error";
    }

    @GetMapping("/admin")
    public String admin() {
        return "admin"; // 返回管理员页面视图
    }


    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }


}